<?php

namespace app\admin\controller\separate_order;

use app\api\model\SeparateSet;
use app\api\model\ShareAccount;
use app\common\controller\Backend;
use think\Request;
use think\Session;
use wechat\WechatController;

class ShareAccounts  extends Backend
{
    protected $searchFields = 'separate_accounts.id,order_id';
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new ShareAccount();
        $this->service_secret = Session::get('admin')['secret'];
        if(!empty($this->service_secret)){
            $this->model->alias("share_account")
                ->where(['share_account.service_secret'=>$this->service_secret]);
        }
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('store')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    public function retransmission($ids = null){
        $res = $this->model->where(['id'=>$ids])->find();
        $secret = SeparateSet::get(['secret'=>$this->service_secret]);
        $wechat = new WechatController($res->sub_mch_id,$secret);
        $res = $wechat->share(['order_id'=>$res->order_id,'sub_mch_id'=>$res->sub_mch_id]);
        if ($res['result_code'] == 'FAIL'){
            $this->error($res['result_message']);
        }else{
            $this->success("SUCCESS","separate_order/share_accounts?addtabs=1");
        }
    }
}